import {StyleSheet, Text, TouchableOpacity, View, FlatList} from 'react-native'
import React, {useEffect, useState} from 'react'
import PageScrollView from "@/components/PageScrollView";
import PageTabBar from "@/components/PageTabBar";
import FcTextInput from "@/components/FcTextInput";
import FcButton from "@/components/FcButton";
import FcModal from '@/components/FcModal';
import NoData from "@/components/NoData";
import {Toast} from "@ant-design/react-native";
import {useDispatch} from "react-redux";
import {router, useLocalSearchParams} from "expo-router";
import {set_rowData} from "@/store/reducer/contentManage/contentManageSlice";

import {
  useGetTagListMutation,
  useAddGroupMutation,
  useEditGroupMutation,
  useDeleteGroupMutation,
} from "@/store/api/contentManage/contentManageApi";

type Props = {}

const grouping = (props: Props) => {
  const [tagList,setTagList] = useState<any>([])
  const [count,setCount] = useState<any>(0)
  const [deleteOpen, setDeleteOpen] = useState(false)
  const [type, setType] = useState('add')
  const [searchText, setSearchText] = useState('')
  const [addGroupOpen, setAddGroupOpen] = useState(false)
  const [groupItem, setGroupItem] = useState<any>({})
  
  const [getTagListFun] = useGetTagListMutation()
  const [addGroupFun] = useAddGroupMutation()
  const [editGroupFun] = useEditGroupMutation()
  const [deleteGroupFun] = useDeleteGroupMutation()

  const dispatch = useDispatch()
  
  useEffect(() => {
    getTagList()
  }, [])

  // 获取标签列表
  const getTagList = () => {
    getTagListFun({}).then(res => {
      if(res.data.code === 200){
        setTagList(res.data.result.records)
      }
    })
  }

  //选择产品
  const handleCheckChange = (index:any) => {
    let arr = JSON.parse(JSON.stringify(tagList))
    arr[index].checked = !arr[index].checked
    setTagList(arr)

    let count = arr.filter((val:any) => val.checked).length
    setCount(count)
  }

  // 新增分组
  const handleAddGroup = () => {
    if(groupItem.id){
      editGroupFun({id: groupItem.id, name: groupItem.name}).then(res => {
        if (res.data.code === 200) {
          Toast.info('编辑成功')
          getTagList()
        }
      })
    }else{
      addGroupFun({id: null, name: groupItem.name}).then(res => {
        if (res.data.code === 200) {
          Toast.info('新增成功')
          getTagList()
        }
      })
    }
  }

  // 删除产品
  const handleDelete = () => {
    let arr = tagList.filter((val:any) => val.checked).map((val:any) => val.id)

    deleteGroupFun({ids: arr.join()}).then(res => {
      if (res.data.code === 200) {
        Toast.info('删除成功')
        setCount(0)
        getTagList()
      }
    })
  }

  return (
    <PageScrollView
      pageTab={
        <PageTabBar
          style={{marginVertical: 10}}
          title='内容分组'
          right={
            type == 'add' ? 
            <View style={{display: 'flex', flexDirection: 'row'}}>
              <TouchableOpacity onPress={() => setType('edit')}>
                <Text style={[styles.page_header_right, {marginRight: 5}]}>编辑</Text>
              </TouchableOpacity>
              <TouchableOpacity onPress={() => {setGroupItem({}); setAddGroupOpen(true)}}>
                <Text style={styles.page_header_right}>新增分组</Text>
              </TouchableOpacity>
            </View>
            : 
            <TouchableOpacity>
              <FcButton
                onClick={() => setType('add')}
                type='BjJB'
                colors={['#6989FF', '#C65EFD']}
                style={{width: 48, height: 28, justifyContent: 'center'}}
                itemStyle={{borderRadius: 8, fontSize: 12}}
                textName='完成'
              />
            </TouchableOpacity>
          }
        />
      }
      pageBottom = {
        type == 'edit' ?

        <View style={styles.page_bottom}>
          <Text style={{color: 'rgba(0, 0, 0, 0.3)'}}>已选{ count }个</Text>
          <TouchableOpacity style={{display: 'flex', flexDirection: 'row', alignItems: 'center'}} onPress={() => {if(count > 0) setDeleteOpen(true)}}>
            <Text style={{fontFamily: 'FcIconFont', fontSize: 18, color: count > 0 ? '#000' : 'rgba(0, 0, 0, 0.3)', marginRight: 5}}>&#xe61d;</Text>
            <Text style={{color: count > 0 ? 'rgba(250,81,81,1)' : 'rgba(250,81,81,.3)'}}>删除</Text>
          </TouchableOpacity>
        </View>
        
        : null
      }
      pageHeader={
        <FcTextInput 
          type='search' 
          text={searchText} 
          placeholder={'请输入要搜索的内容'}
          onChangeText={setSearchText}
          style={{marginHorizontal: 10}}
          inputStyle={{backgroundColor: 'white', lineHeight: 20}}
          bodyStyle={{backgroundColor: 'white'}}
          height={40}
        />
      }
    >
      <View>
        {
          tagList.filter((item:any) => item.name.includes(searchText)).length == 0 ?
          <View style={{flexDirection: 'column',alignItems: 'center',justifyContent: 'center',paddingTop: 60,paddingBottom: 120}}>
            <NoData hintText='暂无分组'/>
            <FcButton
              onClick={() => {setGroupItem({}); setAddGroupOpen(true)}}
              type='BjJB'
              colors={['#6989FF', '#C65EFD']}
              style={{width: 74, height: 32, justifyContent: 'center'}}
              itemStyle={{borderRadius: 8}}
              textName='去新增'>
            </FcButton>
          </View>
          : 
          <FlatList
            data={tagList.filter((item:any) => item.name.includes(searchText))}
            renderItem={({item,index}) => (
              <View style={styles.list_item}>
                {
                  type == 'edit' ?
                  <TouchableOpacity style={[styles.select_icon, item.checked && styles.select_active]} onPress={() => {handleCheckChange(index)}}>
                    {item.checked && <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'white'}}>&#xe64d;</Text>}
                  </TouchableOpacity>
                  : null
                }
                <View style={{flex: 1, display: 'flex', flexDirection: 'row'}}>
                  <Text style={styles.list_item_title}>{ item.name }</Text>
                  {
                    type == 'edit' ?
                    <View style={{display: 'flex', flexDirection: 'row'}}>
                      <TouchableOpacity onPress={() => {setGroupItem(item); setAddGroupOpen(true)}}>
                        <Text style={{fontFamily: 'FcIconFont',fontSize: 20,color: '#000', marginRight: 15}}>&#xe630;</Text>
                      </TouchableOpacity>
                      <TouchableOpacity>
                        <Text style={{fontFamily: 'FcIconFont',fontSize: 20,color: '#000'}}>&#xe633;</Text>
                      </TouchableOpacity>
                    </View>
                    : null
                  }
                </View>
              </View>
            )}
            keyExtractor={(_, index) => `list_item${index}`}
          />
        }

        {/* 新增/编辑分组弹窗 */}
        <FcModal
          isOpen={addGroupOpen}
          transparent
          closeShow={false}
          animationType='fade'
          onFcModalClose={() => setAddGroupOpen(false)}
          style={{width: 280, borderBottomRightRadius: 12, borderBottomLeftRadius: 12}}
          titleText={groupItem.id ? '编辑分组' : '新增分组'}
          titleBottomBorderWidth={0}
          footer={[
            {
              text: '取消',
              onPress: () => setAddGroupOpen(false),
              style: { color: 'rgba(0, 0, 0, 0.5)',fontSize: 17 },
            },
            {
              text: '确认',
              onPress: () => handleAddGroup(),
              style: { color: '#2856FF',fontSize: 17 },
            },
          ]}
        >
          <View style={{paddingBottom: 20}}>
            <FcTextInput 
              multiline 
              text={groupItem.name} 
              placeholder={'请输入分组名称'}
              onChangeText={(val) => setGroupItem({...groupItem, name: val})}
              height={45}
            />
          </View>
        </FcModal>

        {/* 删除弹窗 */}
        <FcModal
          isOpen={deleteOpen}
          transparent
          closeShow={false}
          animationType='fade'
          onFcModalClose={() => setDeleteOpen(false)}
          style={{width: 280, borderBottomRightRadius: 12, borderBottomLeftRadius: 12}}
          titleText={'确认要删除吗？'}
          titleBottomBorderWidth={0}
          footer={[
            {
              text: '取消',
              onPress: () => setDeleteOpen(false),
              style: { color: 'rgba(0, 0, 0, 0.5)',fontSize: 17 },
            },
            {
              text: '确认',
              onPress: () => handleDelete(),
              style: { color: '#2856FF',fontSize: 17 },
            },
          ]}
        >
          <Text style={{textAlign:'center',color: 'rgba(0,0,0,0.5)'}}>一旦删除，当前分组将被删除哦~</Text>
        </FcModal>
      </View>
    </PageScrollView>
  )
}

export default grouping

const styles = StyleSheet.create({
  page_header_right: {
    width: 64,
    height: 28,
    lineHeight: 28,
    borderRadius: 8,
    fontSize: 12,
    textAlign: 'center',
    color: '#2856FF',
    backgroundColor: 'rgba(255, 255, 255, 0.5)',
  },
  page_bottom: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    height: 56,
    paddingHorizontal: 16,
    backgroundColor: '#FFF',
  },
  select_icon: {
    width: 20,
    height: 20,
    borderRadius: '50%',
    borderWidth: 1,
    borderColor: 'rgba(0,0,0,0.5)',
    marginRight: 12,
  },
  select_active: {
    borderColor: '#2856FF',
    backgroundColor: '#2856FF',
    flexDirection: 'row',
    alignItems: "center",
    justifyContent: "center"
  },
  list_item: {
    height: 56,
    borderRadius: 8,
    marginBottom: 8,
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    borderBottomWidth: 1,
    borderBottomColor: 'rgba(0, 0, 0, 0.1)',
  },
  list_item_title: {
    flex: 1,
    fontSize: 15, 
    marginRight: 12,
  },
})